package net.wanho.interceptor;

import net.wanho.util.CurrentUtil;
import net.wanho.util.JwtUtil;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录拦截器
 */
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 判断请求头中是否有token，如果没有，则直接拒绝
        String authorization = request.getHeader("Authorization");
        if(StringUtils.isEmpty(authorization)){
            throw new RuntimeException("请先登录再操作！");
        }

        // 如果有token，判断是否有效
        String token = authorization.replace("Bearer ", "");
        if(!JwtUtil.valid(token)){
            throw new RuntimeException("token无效，请重新登录！");
        }

        // 获取当前用户id，并保存到ThreadLocal中
        Integer id = JwtUtil.parseInteger(token, "userId");
        CurrentUtil.setUserId(id);

        return true;
    }
}
